#{extends 'main.html' /}
#{set 'title'}&{'admin.projects.indicators.page.title'}#{/set}

<h1>Indicators</h1>



<!-- widget grid -->
<section id="widget-grid" class="">

	<!-- row -->
	<div class="row">

		<!-- NEW WIDGET START -->
		<article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">

			<form action="/admin/projects/loadIndicators" method="POST" enctype="multipart/form-data" role="form">
				<input type="file" id="file" name="file">
				<input type="submit" value="Load it...">
			</form>

			<table id="jqgrid"></table>
			<div id="pjqgrid"></div>

		</article>
		<!-- WIDGET END -->

	</div>

	<!-- end row -->
</section>
<!-- end widget grid -->


<div id="indicator-tree-dialog" style="display:none">
</div>

#{set 'pageCSSs'}
	<link rel="stylesheet" type="text/css" media="screen" href="/public/javascripts/aciTree/css/aciTree.css">
#{/set}

#{set 'pageScripts'}
<script src="/public/js/plugin/jqgrid/jquery.jqGrid.min.js"></script>
<script src="/public/js/plugin/jqgrid/grid.locale-en.min.js"></script>
<script src="/public/javascripts/aciTree/js/jquery.aciPlugin.min.js"></script>
<script src="/public/javascripts/aciTree/js/jquery.aciTree.min.js"></script>
#{/set}


#{set 'pageOnLoadScriptCode'}

	$("#jqgrid").jqGrid({
		url: "/admin/projects/indicatorsList",
		datatype: "json",
		colNames: [ '','','','Numeral', 'Name', 'Description', 'Measure','Options'],
		colModel: [
			{name: 'id', width: 10, key: true, hidden: true},
			{name: 'indicator.id', editable:true, hidden: true},
			{name: 'indicator.parent.id', editable:true, hidden: true},
			{name: 'indicator.numeral', width: 200, editable:true, sortable: false},
			{name: 'indicator.name', width: 200, editable:true, sortable: false},
			{name: 'indicator.description', width: 200, editable:true, sortable: false},
			{name: 'indicator.measure', width: 200, editable:true, sortable: false},
			{name: 'options', width: 200},
		],
		sortname: 'indicator.numeral',
		sortorder: "asc",
		hiddengrid: true,
		gridview: true,
		treeGrid: true,
		treeGridModel: "adjacency",
		ExpandColumn: 'indicator.numeral',
		ExpandColClick: true,
		jsonReader: { repeatitems: false, root: function (obj) { return obj; } },
		height: "auto",
		editurl : "/admin/projects/editIndicator",
		pager : '#pjqgrid',
		autowidth : true,
		gridComplete : function() {
			var ids = jQuery("#jqgrid").jqGrid('getDataIDs');
			
			for (var i = 0; i < ids.length; i++) {
				var cl = ids[i];
				var indicatorField = jQuery("#jqgrid"). getRowData(cl)["indicator.id"];
				var indicatorId = 0;
				if (!isNaN(indicatorField)){
					indicatorId = parseInt(indicatorField)
				}
				
				var visibleMainButtons = "";
				var visibleOnEditButtons = "";

				if(indicatorId > 0) {
					//Existing records
					visibleOnEditButtons = "style='display:none;'"
				} else {
					//New record
					visibleMainButtons = "style='display:none;'"
				}

				var addButton =		"<button class='btn btn-xs btn-default' id='btn-add-"+cl+"' "+visibleMainButtons+" data-original-title='Add' onclick=\"addChildNode(" + cl + ","+indicatorId+");\"><i class='fa fa-plus'></i></button>";
				var moveButton =	"<button class='btn btn-xs btn-default' id='btn-move-"+cl+"' "+visibleMainButtons+" data-original-title='Change Parent' onclick=\"changeParent(" + indicatorId + ");\"><i class='fa fa-arrows'></i></button>";
				var deleteButton =	"<button class='btn btn-xs btn-default' id='btn-delete-"+cl+"' "+visibleMainButtons+" data-original-title='Delete Row' onclick=\"deleteNode("+indicatorId+");\"><i class='fa fa-trash-o'></i></button>";
				var editButton =	"<button class='btn btn-xs btn-default' id='btn-edit-"+cl+"' "+visibleMainButtons+" data-original-title='Edit Row' onclick=\"editRow("+cl+");\"><i class='fa fa-pencil'></i></button>";
				var updateButton =	"<button class='btn btn-xs btn-default' id='btn-update-"+cl+"' "+visibleOnEditButtons+" data-original-title='Save Row' onclick=\"updateRow("+cl+");\"><i class='fa fa-save'></i></button>";
				var restoreButton =	"<button class='btn btn-xs btn-default' id='btn-restore-"+cl+"' "+visibleOnEditButtons+"data-original-title='Cancel' onclick=\"restoreRow("+cl+");\"><i class='fa fa-times'></i></button>";
				var removeButton =	"<button class='btn btn-xs btn-default' id='btn-remove-"+cl+"' "+visibleOnEditButtons+" data-original-title='Delete Row' onclick=\"deleteRow("+cl+");\"><i class='fa fa-times'></i></button>";

				jQuery("#jqgrid").jqGrid('setRowData', ids[i], {
					options : addButton + moveButton +editButton + deleteButton + updateButton + removeButton + restoreButton
				});				
			}
		}
	});
	
	jQuery("#jqgrid").jqGrid('navGrid', "#pjqgrid", {
		edit : false,
		add : true,
		del : false,
		search : false,
		refresh : false
	},{},{closeAfterAdd:true},{});

#{/set}



#{set 'pageScriptCode'}

	var isGridInEditMode = function () {
		var editing = false;
		$.each($('#jqgrid').jqGrid('getDataIDs'),function(index, value) {
			if ($("tr#"+value).attr("editable") && $("tr#"+value).attr("editable") === "1") {
				editing = true;
				return false;
			}
		});
		return editing;	
	}

	var deleteNode = function(indicatorId) {
		jQuery('#jqgrid').jqGrid('delGridRow', indicatorId, {reloadAfterSubmit:true} );
	}

	var deleteRow = function(id) {
		jQuery('#jqgrid').jqGrid('delRowData',id);
	}

	var editRow = function(rowId, isNew) {
		if (isGridInEditMode()) {
			alert("Exists one row in Edit Mode");
			return ;
		}
		jQuery('#jqgrid').editRow(rowId);

		$("#btn-add-"+rowId).hide();
		$("#btn-move-"+rowId).hide();
		$("#btn-edit-"+rowId).hide();
		$("#btn-delete-"+rowId).hide();
		$("#btn-update-"+rowId).show();

		if (isNew) {
			$("#btn-restore-"+rowId).hide();
			$("#btn-remove-"+rowId).show();
		} else {
			$("#btn-restore-"+rowId).show();
			$("#btn-remove-"+rowId).hide();
		}
	}

	var restoreRow = function(rowId) {
		jQuery('#jqgrid').restoreRow(rowId);
		defaultButtons(rowId);
	}

	var updateRow = function(rowId) {
		jQuery('#jqgrid').saveRow(rowId);
		defaultButtons(rowId);
	}

	var defaultButtons = function(rowId) {
		$("#btn-add-"+rowId).show();
		$("#btn-move-"+rowId).show();
		$("#btn-edit-"+rowId).show();
		$("#btn-delete-"+rowId).show();
		$("#btn-update-"+rowId).hide();
		$("#btn-restore-"+rowId).hide();
		$("#btn-remove-"+rowId).hide();
	}

	var addChildNode = function(rowParentId, parentId) {

		if (isGridInEditMode()) {
			alert("Exist one row in Edit Mode");
			return ;
		}

		var ids = $('#jqgrid').jqGrid('getDataIDs');
		var newChildId = Math.max.apply(Math,$('#jqgrid').jqGrid('getDataIDs')) +1;
		var newChildNodeData = {
				'indicator.id':'',
				'indicator.parent.id':parentId,
				'indicator.numeral':null,
				'actions':'',
				'indicator.name':null,
				'indicator.description':'',
				'indicator.measure':''
			};

		jQuery('#jqgrid').addChildNode(newChildId,rowParentId,newChildNodeData);
		editRow(newChildId,true);
	}

	var addParentNode = function() {
		addChildNode(null,null);
	}

	var changeParent = function(indicatorId) {

		$("#indicator-tree-dialog").append("<div id=\"indicator-tree\" class=\"aciTree aciTreeArrow\" style=\"margin:0\"></div>");

		$('#indicator-tree-dialog').dialog({
			title: 'Change Parent',
			buttons: [
				{
					text: "Ok",
					icons: {
						primary: "ui-icon-heart"
					},
					click: function() {

						var indicatorSelected = $("#indicator-tree .aciTreeChecked").filter(":last");
						
						if (indicatorSelected.length == 0) {
							alert ("Please, select a parent")
						} else {
							var newParentId = getSelectedIndicator();
							if(indicatorId != newParentId){
								$("#indicator-tree").remove();
								$.ajax({
									url: "/admin/projects/editIndicator",
									data: {
										oper : 'move',
										newParentId : newParentId,
										id : indicatorId // current indicator id
									},
								});
							} else {
								alert ("Please, select a different parent unable to move to the same row")
							}
						}
						$( this ).dialog( "close" );
					}
				},
				{
					text: "Cancel",
					icons: {
						primary: "ui-icon-heart"
					},
					click: function() {
						$("#indicator-tree").remove();
						$( this ).dialog( "close" );
					}
				},
				{
					text: "Set to parent",
					icons: {
						primary: "ui-icon-heart"
					},
					click: function() {
						alert ("Setting current record to parent level")
						$("#indicator-tree").remove();

						$.ajax({
							url: "/admin/projects/editIndicator",
							data: {
								oper : 'move',
								newParentId : 0,
								id : indicatorId // current indicator id
							},
						});
						$( this ).dialog( "close" );
					}				
				}
			],
			resizable: true,
			width: 345,
			height: 420,
			resize: $resize,
			modal: true
		});

		// init/resize
		$resize.call($('#indicator-tree-dialog'));

		// init the tree
		$('#indicator-tree').aciTree({
			ajax: {
				url: '/admin/projects/indicatorsTreeList?indicatorId='+indicatorId
			},
			fullRow:true,
			radio: true,
			radioBreak: true,
			columnData:[{props:'indicatorId'}],
			itemHook: function(parent, item, itemData, level) {
				$hideColumn(item);
			}
		});
	}

	var $hideColumn = function (item) {
		if (item.children().filter(":first").hasClass("aciTreeColumn")) {
			item.children().filter(":first").hide();
		} else {
			$hideColumn(item.children());
		}
	}

	var getSelectedIndicator = function () {
		var item = $selectedRow($("#indicator-tree .aciTreeChecked").filter(":last"));
		return parseInt(item.text());
	}

	var $selectedRow = function (item) {
		if (item.children().filter(":first").hasClass("aciTreeColumn")) {
			return item.children().filter(":first");
		} else {
			return $selectedRow(item.children());
		}
	}

	// resize the aciTree container
	var $resize = function(event, ui) {
		$(this).find('.aciTree').css({
			width: $(this).width() - 20 + 'px',
			height: $(this).height() - 30 + 'px'
		});
	};

#{/set}